package com.example.testnetdemo

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.telephony.TelephonyManager
import android.view.View
import android.widget.Toast
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_main.*
import android.provider.Telephony.Carriers.MNC
import android.provider.Telephony.Carriers.MCC
import android.telephony.gsm.GsmCellLocation
import android.content.Context.TELEPHONY_SERVICE
import android.os.Handler
import android.os.Message
import androidx.core.content.ContextCompat.getSystemService
import android.telephony.cdma.CdmaCellLocation
import android.telephony.CellSignalStrengthCdma
import android.telephony.CellIdentityCdma
import android.telephony.CellInfoCdma
import android.telephony.CellInfo
import android.text.format.Formatter
import com.example.testnetdemo.model.LzyResponse
import com.example.testnetdemo.utils.JsonCallback
import kotlinx.android.synthetic.main.activity_siminfo_layout.*
import com.example.testnetdemo.utils.NetWorkSpeedUtils
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.AbsCallback
import com.lzy.okgo.callback.FileCallback
import com.lzy.okgo.model.Progress
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import java.io.File
import java.text.NumberFormat


class MainActivity : AppCompatActivity(), View.OnClickListener {

    private var isOpenPermission = false

    private val netWorkSpeedUtils by lazy {
        NetWorkSpeedUtils(this, mHandler)
    }
    private val numberFormat: NumberFormat by lazy {
        NumberFormat.getPercentInstance()
    }

    private var downMaxSpeed = 0L
    private var downAverage = 0
    private var startDownTime = 0L
    private var stopDownTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        btn_phone_info.setOnClickListener(this)
        btn_down.setOnClickListener(this)
        btn_up.setOnClickListener(this)
        btn_net.setOnClickListener(this)

        getPermissions()
    }

    override fun onClick(p0: View?) {
        if (!isOpenPermission) {
            getPermissions()
            return
        }
        when (p0?.id) {
            R.id.btn_phone_info -> {
                SIMInfoActivity.start(this)
            }
            R.id.btn_down -> {
                down()
            }
            R.id.btn_up -> {

            }
            R.id.btn_net -> {
                netWorkSpeedUtils.stop()
                netWorkSpeedUtils.startShowNetSpeed()
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun getPermissions() {
        RxPermissions(this)
            .request(
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_SMS,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_FINE_LOCATION
            )
            .subscribe {
                isOpenPermission = it
                if (!it) {
                    Toast.makeText(this, "请打开权限", Toast.LENGTH_SHORT).show()
                }
            }
    }

    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                100 -> tv_net.text = "当前网速： " + msg.obj.toString()
            }
            super.handleMessage(msg)
        }
    }

    private fun down() {
        OkGo.get<File>("https://downpack.baidu.com/appsearch_AndroidPhone_1012271b.apk")
            .tag(this)
            .execute(
                object : FileCallback("alipay.apk") {

                    override fun onStart(request: Request<File, out Request<*, *>>?) {
                        startDownTime = System.currentTimeMillis()
                        Toast.makeText(this@MainActivity, "开始下载", Toast.LENGTH_SHORT).show()
                    }

                    @SuppressLint("SetTextI18n")
                    override fun onSuccess(response: Response<File>) {
                        stopDownTime = System.currentTimeMillis()

                        val speed =
                            response.body().length() / ((stopDownTime - startDownTime) / 1000)
                        tv_down_average.text =
                            "均速：${Formatter.formatFileSize(applicationContext, speed)}/S"

                        val max = Formatter.formatFileSize(applicationContext, downMaxSpeed)
                        tv_down_max.text = "最大速度：$max/S"
                        Toast.makeText(this@MainActivity, "下载完成", Toast.LENGTH_SHORT).show()
                    }

                    override fun onError(response: Response<File>) {
                        Toast.makeText(this@MainActivity,  "下载出错 ${response.exception}", Toast.LENGTH_SHORT).show()
                    }

                    @SuppressLint("SetTextI18n")
                    override fun downloadProgress(progress: Progress?) {
                        progress?.let {
                            if (progress.speed > downMaxSpeed) {
                                downMaxSpeed = progress.speed
                            }
                            val downloadLength =
                                Formatter.formatFileSize(applicationContext, progress.currentSize)
                            val totalLength =
                                Formatter.formatFileSize(applicationContext, progress.totalSize)
                            tv_down_size.text = "$downloadLength/$totalLength"
                            val speed = Formatter.formatFileSize(applicationContext, progress.speed)
                            tv_down_speed.text = String.format("%s/S", speed)
                            tv_down_progress.text =
                                numberFormat.format(progress.fraction.toDouble())
                            progress_down.max = 10000
                            progress_down.progress = (progress.fraction * 10000).toInt()
                        }
                    }
                })
    }

    private fun up(file: File) {
        //拼接参数
        OkGo.post<LzyResponse<Any>>("")
            .tag(this)
            .headers("header1", "headerValue1")
            .params("param1", "paramValue1")
            .params("file1", file)   //这种方式为一个key，对应一个文件
            .execute(object : JsonCallback<LzyResponse<Any>>() {
                override fun onStart(request: Request<LzyResponse<Any>, out Request<*, *>>) {
//                    btnFormUpload.setText("正在上传中...")
                }

                override fun onSuccess(response: Response<LzyResponse<Any>>) {
//                    handleResponse(response)
//                    btnFormUpload.setText("上传完成")
                }

                override fun onError(response: Response<LzyResponse<Any>>) {
//                    handleError(response)
//                    btnFormUpload.setText("上传出错")
                }

                override fun uploadProgress(progress: Progress) {
                    println("uploadProgress: $progress")

//                    val downloadLength =
//                        Formatter.formatFileSize(applicationContext, progress.currentSize)
//                    val totalLength =
//                        Formatter.formatFileSize(applicationContext, progress.totalSize)
//                    tvDownloadSize.setText("$downloadLength/$totalLength")
//                    val speed = Formatter.formatFileSize(applicationContext, progress.speed)
//                    tvNetSpeed.setText(String.format("%s/s", speed))
//                    tvProgress.setText(numberFormat.format(progress.fraction.toDouble()))
//                    pbProgress.setMax(10000)
//                    pbProgress.setProgress((progress.fraction * 10000).toInt())
                }
            })
    }

    override fun onDestroy() {
        super.onDestroy()
        OkGo.getInstance().cancelTag(this)
        netWorkSpeedUtils.stop()
        mHandler.removeCallbacksAndMessages(null)
    }

}
